package cc.rico.tutorial;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Created by rico on 2018/8/19.
 */
public class ZkConnectionDemo {
    private static final Logger logger = LoggerFactory.getLogger(ZkConnectionDemo.class);

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        ZooKeeper zk = new ZooKeeper("192.168.223.140:2181", 4000, new CustomWatcher());

        String path = "/ZkConnectionDemo";
        Stat stat = zk.exists(path, false);
        if(stat == null) {
            String result = zk.create(path, "ZkConnectionDemo".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            logger.info("##result = {}", result);
        }

        byte[] bytes = zk.getData(path, false, stat);
        logger.info("data = {}", new String(bytes));
    }

    public static class CustomWatcher implements Watcher {
        @Override
        public void process(WatchedEvent event) {
            logger.info("##WatchedEvent.state = {}", event.getState());
            logger.info("##WatchedEvent.path = {}", event.getPath());
            logger.info("##WatchedEvent.Type = {}", event.getType());
        }
    }

}
